<?php
class App_Source_Blogs_Mapper extends Mozg_Mapper_Data
{
	private $_source;

	protected $_entityPath = 'entity/blog';

	public function __construct()
	{
		$this->_source = Mozg_Source::get('default');
	}

	private function GetSqlFromFilter($filter = null)
	{
		$sqlFilter = array('where' => array(), 'join' => array());
		if (!($filter instanceof Mozg_Property_Params)) $filter = $this->GetFilter($filter);

		if ($filter->HasSet('userId'))
		{
			$sqlFilter['where'][] = 'mb.user_id = ' .(int)$filter->GetUserId();
		}

		if ($filter->HasSet('id'))
		{
			$sqlFilter['where'][] = 'mb.id = ' .(int)$filter->GetId();
		}

		$sqlFilter['where'] = sizeof($sqlFilter['where']) ? '(' .implode(') and (', $sqlFilter['where']). ')' : '';
		$sqlFilter['join'] = sizeof($sqlFilter['join']) ?  implode(' ', $sqlFilter['join']) : '';

		return $sqlFilter;
	}

	private $_totalRows = 0;

	public function GetTotalRows()
	{
		if (!is_int($this->_totalRows))
		{
			$this->_totalRows = $this->_source->query("SELECT FOUND_ROWS()")->fetchColumn();
		}

		return $this->_totalRows;
	}

	protected function Find($filter = null, Mozg_Paginator $paginator = null, $fields = array())
	{
		$sqlFilter = $this->GetSqlFromFilter($filter);

		$this->_totalRows = null;

        $rows = $this->_source->fetchObjectAll("SELECT " .($paginator ? "SQL_CALC_FOUND_ROWS" : "" ). "
												" .$this->_source->Table('blog')->GetSqlMap($fields, 'mb'). ",
												" .$this->_source->Table('users')->GetSqlMap(array(), 'u', 'user'). "
						                     FROM
						                     	%%blog%% mb
						                     		left join %%users%% u on(mb.user_id = u.user_id)
						                     " .($sqlFilter['where'] ? " WHERE ". $sqlFilter['where'] : ""). "
							                 ORDER by id
							                 " .($paginator ? "LIMIT " .$paginator->GetSqlLimit() : ""). "
							               ", $this->_entityPath);

        return $rows;
	}

	public function GetList($filter = null, Mozg_Paginator $paginator = null)
	{
		return $this->Find($filter, $paginator, array('user_id' => 0));
	}

	public function GetOne($filter = null)
	{
		return current($this->Find($filter, new Mozg_Paginator(1,1), array('user_id' => 0)));
	}

	public function Save(Mozg_Property_Params $obj)
	{
		if (!$obj->Validator()->Validate()) return false;

		$this->Prepare($obj);

		if ($obj->GetId())
		{
			$filter = $this->GetFilter();
			$filter->SetId($obj->GetId());
			return $this->Update($obj, $filter);
		}

		return $this->Insert($obj);
	}

	protected function Insert(Mozg_Property_Params $obj)
	{
		$fields = $this->_source->Table('blog')->GetSqlInsert($obj);
		$num = $this->_source->exec("INSERT INTO %%blog%%(" .$fields['fields']. ") VALUES (" .$fields['values']. ")");

		if ($num)
		{
			$obj->SetId($this->_source->lastInsertID());
			return true;
		}

		return false;
	}

	protected function Update(Mozg_Property_Params $obj, $filter = null)
	{
		$sqlFilter = $this->GetSqlFromFilter($filter);

		$updateStr = $this->_source->Table('blog')->GetSqlUpdate($obj, 'mb');
		if (!strlen($updateStr)) return true;

		$num = (bool)$this->_source->exec("update %%blog%% mb
										      set
												 " .$updateStr. "
											  " .($sqlFilter['where'] ? " WHERE ". $sqlFilter['where'] : ""). "
									     ");

		if ($num)
		{
			return true;
		}

		return false;
	}

	protected function Prepare(Mozg_Property_Params $obj)
	{

	}

    public function Delete($filter = null)
    {
    	$sqlFilter = $this->GetSqlFromFilter($filter);

        $num = (bool)$this->_source->exec("DELETE
        											mb, mae, maec
		        								FROM %%blog%% mb
		        										left join %%article_entry%% mae on (mb.id = mae.blog_id)
		        										left join %%article_entry_comment%% maec on (mae.id = maec.entry_id)
		        										left join %%tag%% mt on (mae.id = mt.id AND area = 'articles')
		        								" .($sqlFilter['where'] ? " WHERE ". $sqlFilter['where'] : ""). "
		        								");
    	if ($num)
    	{
    		return true;
    	}
    	return false;
    }
}